package servlets;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cityOperations.CitySessionBean;
import dataEntity.City;


/**
 * Servlet implementation class GetCitiesByPopServelet
 */
@WebServlet("/GetCitiesByPopServlet")
public class GetCitiesByPopServlet extends HttpServlet {


	@EJB
	CitySessionBean bean;
	
       
    /**
	 * 
	 */
	private static final long serialVersionUID = -6180168201007593097L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public GetCitiesByPopServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sess = request.getSession();
		
		//Retrieve the value that the user has put in the text field
		String popThresholdStr = request.getParameter("populationTextField");
		int popThreshold = 0;
		
		try{
			popThreshold = Integer.valueOf(popThresholdStr.trim());
		}
		catch (NumberFormatException nfe) {
			PrintWriter out = response.getWriter();
			out.write("Dati inseriti non validi");//nfe.getMessage());
			nfe.printStackTrace();
			return;
		}
		catch (Exception e) {
			PrintWriter out = response.getWriter();
			out.write("ERRORE");
			out.write(e.getMessage());
			e.printStackTrace();
			return;
		}
		
		List<City> lCity = bean.getCities_MoreThan(popThreshold);
		sess.setAttribute("cities", lCity);
		
		RequestDispatcher dispatcher;
	    dispatcher = getServletContext().getRequestDispatcher(
	          "/showCitiesByPopulation.jsp");
	    dispatcher.forward(request,response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
